package com.pug.security.service.impl;

import com.pug.security.mapper.UserMapper;
import com.pug.security.po.SysPermission;
import com.pug.security.po.SysRole;
import com.pug.security.po.SysUser;
import com.pug.security.vo.UserDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.security.auth.login.LoginContext;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author RenGaoshuai
 * @date 2023/7/17 9:16
 * @description 自定义的查询数据库接口
 */
@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名查询瀛湖信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("进入自定义userDetailsService方法，用户名为：{}",username);
        UserDetailVO userVO = new UserDetailVO();

        //查询用户
        SysUser sysUser = userMapper.loadByUsername(username);


        if (Objects.nonNull(sysUser)) {

            //查询角色
            List<SysRole> sysRoles = userMapper.loadRoleByUserId(sysUser.getId());
            //查询权限
            List<SysPermission> sysPermissions = userMapper.loadPermissionByUserId(sysUser.getId());

            //容器
            Set<GrantedAuthority> authorities = new HashSet<>();

            if (!CollectionUtils.isEmpty(sysRoles)) {
                sysRoles.forEach(role -> {
                    authorities.add(new SimpleGrantedAuthority(role.getEnname()));
                });
            }

            if (!CollectionUtils.isEmpty(sysPermissions)) {
                sysPermissions.forEach(per -> {
                    authorities.add(new SimpleGrantedAuthority(per.getEname()));
                });
            }


            userVO.setSysUser(sysUser);
            userVO.setUsername(sysUser.getUsername());
            userVO.setPassword(sysUser.getPassword());
            userVO.setAuthorities(authorities);
        }
        log.info("退出自定义userDetailsService方法，用户名为：{}",username);
        return userVO;
    }
}
